package tasks

import (
	"ci-control-backend/common/hostConn"
	"ci-control-backend/model"
	"ci-control-backend/tools"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"strings"
	"sync"
	"time"
)

var (
	mutex *sync.Mutex
)

func init() {
	mutex = new(sync.Mutex)
}

func newTask(record *model.Record) gin.H {
	return gin.H{
		"pipeline_script": record.PipelineScript,
		"push_keys":       record.PushKeys,
	}
}

func AddTask(plan *model.Plan) error {
	mutex.Lock()
	defer mutex.Unlock()

	hostIds := strings.Split(plan.ExecHosts, ",")
	for _, hostId := range hostIds {
		connInfo := hostConn.Get(hostId)
		if connInfo != nil {
			key, _ := tools.RandomStr(32)
			record := &model.Record{
				PlanID:         plan.ID,
				PlanName:       plan.PlanName,
				PipelineScript: plan.PipelineScript,
				ExecHosts:      hostId,
				PushKeys:       key,
				StartTime:      tools.TimePtr(time.Now()),
			}

			_, err := record.Insert()
			if err != nil {
				return errors.WithStack(err)
			}

			connInfo.Conn.SSEvent("message", gin.H{
				"type": "task",
				"data": newTask(record),
			})
			connInfo.Conn.Writer.Flush()

			return nil
		}
	}
	return errors.New("没有可用主机")
}
